package com.itheima.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.doman.Result;
import com.itheima.doman.pojo.PageResult;
import com.itheima.doman.pojo.StdQueryParam;
import com.itheima.doman.pojo.Student;
import com.itheima.exception.ViolationScoreDeleteException;
import com.itheima.execl.model.StudentModel;
import com.itheima.mapper.StdMapper;
import com.itheima.service.StdService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static com.itheima.constant.MessageConstant.DELETE_VIOLATION_SCORE_SUCCESS;

@Service
public class StdServiceImpl implements StdService {
    private static final Logger log = LoggerFactory.getLogger(StdServiceImpl.class);
    @Autowired
    private StdMapper stdMapper;

    /**
     * 分页查询
     *
     * @param stdQueryParam
     * @return
     */
    @Override
    public PageResult<Student> page(StdQueryParam stdQueryParam) {
        PageHelper.startPage(stdQueryParam.getPage(), stdQueryParam.getPageSize());
        List<Student> empList = stdMapper.list(stdQueryParam);
        Page<Student> p = (Page<Student>) empList;
        return new PageResult(p.getTotal(), p.getResult());
    }

    /**
     * 批量删除
     *
     * @param ids
     */
    @Override
    public void deleteByIds(List<Integer> ids) {
        stdMapper.deleteByIds(ids);
    }

    /**
     * 添加学生
     *
     * @param student
     */
    @Override
    public void addStd(Student student) {
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());
        stdMapper.insertStd(student);
    }

    /**
     * 根据id查询学生信息，回显
     *
     * @param id
     * @return
     */
    @Override
    public Student findById(Integer id) {
        return stdMapper.findById(id);
    }

    /**
     * 修改学生信息
     *
     * @param student
     */
    @Override
    public void update(Student student) {
        student.setUpdateTime(LocalDateTime.now());
        stdMapper.update(student);
    }

    /**
     * 添加违规
     *
     * @param id
     * @param score
     */
    @Override
    public void updateViolation(Integer id, Integer score) {
        Student byId = stdMapper.findById(id);
        byId.setViolationScore(byId.getViolationScore() + score);
        byId.setViolationCount(byId.getViolationCount() + 1);
        stdMapper.update(byId);
        // 判断扣分是否超过40分，如果超过则删除学生
        Student deleteByid = stdMapper.findById(id);
        if (deleteByid.getViolationScore() > 40 || deleteByid.getViolationCount() > 10) {
            stdMapper.deleteByIds(List.of(id));
            throw new ViolationScoreDeleteException(DELETE_VIOLATION_SCORE_SUCCESS);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void importStudent(List<StudentModel> cachedDataList, Integer clazzId) {
        log.info("学生信息导入开始, 共{}条", cachedDataList.size());
        if (!cachedDataList.isEmpty()) {
            List<Student> studentList = cachedDataList.stream().map(sm -> {
                Student student = BeanUtil.copyProperties(sm, Student.class);
                student.setGender(sm.getGenderStr().equals("男") ? 1 : 2);
                student.setIsCollege(sm.getIsCollegeStr().equals("是") ? 1 : 0);
                switch (sm.getDegreeStr()) {
                    case "初中" -> student.setDegree(1);
                    case "高中" -> student.setDegree(2);
                    case "大专" -> student.setDegree(3);
                    case "本科" -> student.setDegree(4);
                    case "硕士" -> student.setDegree(5);
                    case "博士" -> student.setDegree(6);
                }
                student.setClazzId(clazzId);
                student.setCreateTime(LocalDateTime.now());
                student.setUpdateTime(LocalDateTime.now());
                return student;
            }).toList();
            stdMapper.insertBatch(studentList);
        }
        log.info("学生信息导入结束");
    }

    @Override
    public List<StudentModel> list(String name, Integer degree, Integer clazzId) {
        StdQueryParam stdQueryParam = new StdQueryParam();
        stdQueryParam.setName(name);
        stdQueryParam.setDegree(degree);
        stdQueryParam.setClazzId(clazzId);
        List<Student> studentList = stdMapper.list(stdQueryParam);
        if(!studentList.isEmpty()){
            return studentList.stream().map(student -> {
                StudentModel sm = BeanUtil.copyProperties(student, StudentModel.class);
                sm.setGenderStr(student.getGender() == 1 ? "男" : "女");
                sm.setIsCollegeStr(student.getIsCollege() == 1 ? "是" : "否");
                switch (student.getDegree()) {
                    case 1 -> sm.setDegreeStr("初中");
                    case 2 -> sm.setDegreeStr("高中");
                    case 3 -> sm.setDegreeStr("大专");
                    case 4 -> sm.setDegreeStr("本科");
                    case 5 -> sm.setDegreeStr("硕士");
                    case 6 -> sm.setDegreeStr("博士");
                    default -> sm.setDegreeStr("未知");
                }
                return sm;
            }).toList();
        }
        return new ArrayList<>();
    }
}


